package com.yizhu.zczy.system.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yizhu.zczy.common.utils.PageUtils;
import com.yizhu.zczy.common.utils.Query;
import com.yizhu.zczy.system.constant.SystemConstant;
import com.yizhu.zczy.system.entity.MenuEntity;
import com.yizhu.zczy.system.entity.RoleRightsEntity;
import com.yizhu.zczy.system.entity.RoleUserEntity;
import com.yizhu.zczy.system.exception.SystemException;
import com.yizhu.zczy.system.interceptor.MyHandlerInterceptor;
import com.yizhu.zczy.system.service.RoleRightsService;
import com.yizhu.zczy.system.service.RoleUserService;
import com.yizhu.zczy.system.vo.ChangePasswordVo;
import com.yizhu.zczy.system.vo.ShowAdminVo;
import com.yizhu.zczy.system.vo.UserNameAndPassWordVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;


import com.yizhu.zczy.system.dao.UserDao;
import com.yizhu.zczy.system.entity.UserEntity;
import com.yizhu.zczy.system.service.UserService;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpSession;


@Service
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {
    @Autowired
    private RoleUserService roleUserService;
    @Autowired
    private RoleRightsService roleRightsService;
    @Override
    public IPage<ShowAdminVo> queryPage(Long page ,Long limit) {

        IPage<UserEntity> iPage=new Page<>(page,limit);

        IPage<UserEntity> page1 = this.page(iPage, new QueryWrapper<UserEntity>().orderByDesc("create_time"));
        //查询是否有权限
        IPage<ShowAdminVo> userEntityIPage = this.checkPermission(page1);
        return userEntityIPage;
    }

    /**
     * 验证账号密码
     * @param userNameAndPassWordVo
     */
    @Override
    public UserEntity verifyAccountPassword(UserNameAndPassWordVo userNameAndPassWordVo) {
        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("login_name",userNameAndPassWordVo.getUsername());
        UserEntity userEntity = this.getOne(queryWrapper);
        if (userEntity!=null){
            BCryptPasswordEncoder passwordEncoder=new BCryptPasswordEncoder();
            if (passwordEncoder.matches(userNameAndPassWordVo.getPassword(),userEntity.getLoginPwd())){

            }else {
                throw new SystemException("密码不正确");
            }

        }else {
            throw new SystemException("账号不正确");

        }
        return userEntity;
    }



    /**
     * 用户登录
     * @param userNameAndPassWordVo
     * @param session
     */
    @Override
    public void login(UserNameAndPassWordVo userNameAndPassWordVo, HttpSession session) {
        UserEntity userEntity = verifyAccountPassword(userNameAndPassWordVo);
        String sessionCode = (String) session.getAttribute(SystemConstant.USER_LOGIN_CODE);
        if (StringUtils.isEmpty(userNameAndPassWordVo.getCode())){
            throw new SystemException("验证码不能为空");
        }else {
            if (!sessionCode.equalsIgnoreCase(userNameAndPassWordVo.getCode())){
                throw new SystemException("验证码不正确");
            }
            session.setAttribute(SystemConstant.USER_SESSION_SAVE,userEntity);
        }
    }

    /**
     * 修改密码
     * @param passwordVo
     */
    @Override
    public void changePassword(ChangePasswordVo passwordVo) {
        if (!passwordVo.getOldPassword().equals(passwordVo.getConfirmPassword())){
            throw new SystemException("两次密码不正确");
        }
        UserEntity userEntity = MyHandlerInterceptor.threadLocal.get();
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        if (passwordEncoder.matches(passwordVo.getOldPassword(),userEntity.getLoginPwd())){
            userEntity.setLoginPwd(passwordVo.getNewPassword());
            this.updateById(userEntity);
        }else {
            throw new SystemException("密码不正确");
        }

    }

    /**
     * 根据登录的用户查询菜单
     * @return
     */
    @Override
    public List<MenuEntity> queryMenuByLoggedinUser() {
        UserEntity userEntity = MyHandlerInterceptor.threadLocal.get();
        List<MenuEntity> menuEntities=baseMapper.queryMenuByLoggedinUser(userEntity.getUserId());
        List<MenuEntity> menuEntityList = menuEntities.stream().filter(menuEntity -> menuEntity.getLev().equals("1")).map(item->{
            item.setChildern(collectLevel3(menuEntities,item.getFunctioncode()));
            return item;
        }).collect(Collectors.toList());
        return menuEntityList;
    }


    private List<MenuEntity> collectLevel3(List<MenuEntity> menuEntityList, String functioncode) {
        List<MenuEntity> menuEntities = menuEntityList.stream().filter(item -> item.getPmenuId().equals(functioncode)).map(item -> {
            item.setChildern(collectLevel3(menuEntityList, item.getFunctioncode()));
            return item;
        }).collect(Collectors.toList());
        return menuEntities;
    }


    private IPage<ShowAdminVo> checkPermission(IPage<UserEntity> page) {
        List<ShowAdminVo> showAdminVos = page.getRecords().stream().map(userEntity -> {
            ShowAdminVo showAdminVo = new ShowAdminVo();
            BeanUtils.copyProperties(userEntity,showAdminVo);
            QueryWrapper<RoleUserEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id",userEntity.getUserId());
            List<RoleUserEntity> list = roleUserService.list(queryWrapper);
            list.stream().forEach(roleUserEntity -> {
                QueryWrapper<RoleRightsEntity> queryWrapper1 = new QueryWrapper<>();
                queryWrapper.eq("role_id",roleUserEntity.getRoleId());
                List<RoleRightsEntity> roleRightsEntityList = roleRightsService.list(queryWrapper1);
                 roleRightsEntityList.stream().forEach(roleRightsEntity -> {
                     if (roleRightsEntity.getPopedomId()==239){
                           showAdminVo.setHasChanged(true);
                     }
                 });
            });
            return showAdminVo;
        }).collect(Collectors.toList());
        IPage<ShowAdminVo> iPage=new Page();
        iPage.setRecords(showAdminVos);
        iPage.setPages(page.getPages());
        iPage.setCurrent(page.getCurrent());
        iPage.setSize(page.getSize());
        iPage.setTotal(page.getTotal());
        return iPage;
    }

}